package ZmmMoneyLog

import (
	"context"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/os/gtime"
	"github.com/tiger1103/gfast/v3/api/v1/zmm"
	sysservice "github.com/tiger1103/gfast/v3/internal/app/system/service"
	"github.com/tiger1103/gfast/v3/internal/app/zmm/dao"
	"github.com/tiger1103/gfast/v3/internal/app/zmm/model/do"
	"github.com/tiger1103/gfast/v3/internal/app/zmm/model/entity/association"
	"github.com/tiger1103/gfast/v3/internal/app/zmm/service"
)

func init() {
	service.RegisterZmmMoneyLogMember(New())
}

func New() *sZmmMoneyLogMember {
	return &sZmmMoneyLogMember{}
}

type sZmmMoneyLogMember struct {
}

func (s *sZmmMoneyLogMember) GetList(ctx context.Context, req *zmm.ZmmMoneyLogMemberListReq) (total interface{}, list []*association.ZmmMoneyLogMember, err error) {
	where := g.Map{}
	if req.MemberID != "" && req.MemberID != "0" {
		where["member_id"] = req.MemberID
	}
	if req.StartTime != "" {
		where["recharge_time >= ?"] = req.StartTime
	}
	if req.EndTime != "" {
		where["recharge_time <= ?"] = req.EndTime
	}
	if req.TypeData != "" {
		where["type_data"] = req.TypeData
	}

	m := g.Model(association.ZmmMoneyLogMember{})
	cm := m.Clone()
	if req.MemberName != "" {
		where["`zmm_member`.`name` like ?"] = "%" + req.MemberName + "%"
		m.LeftJoin("zmm_member", "zmm_money_log_member.member_id=zmm_member.id").Fields("zmm_money_log_member.*")
		cm.LeftJoin("zmm_member", "zmm_money_log_member.member_id=zmm_member.id")
	}

	total, err = cm.Where(where).Count()

	err = m.WithAll().Where(where).OrderDesc("id").Page(req.PageNum, req.PageSize).FieldsEx("deleted_at").Scan(&list)
	if err != nil {
		return
	}

	return
}

func (s *sZmmMoneyLogMember) SaveMemberLog(ctx context.Context, logEntity *do.ZmmMoneyLogMember) error {
	userInfo := sysservice.Context().GetLoginUser(ctx)
	if userInfo == nil {
		return nil
	}

	_, err := dao.ZmmMoneyLogMember.Ctx(ctx).Insert(do.ZmmMoneyLogMember{
		MemberId:     logEntity.MemberId,
		Money:        logEntity.Money,
		RechargeTime: gtime.Now(),
		AdminId:      userInfo.Id,
		OrderId:      logEntity.OrderId,
		TypeData:     logEntity.TypeData,
		Remark:       logEntity.Remark,
	})
	return err
}
